package work.droit.data.search;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import work.droit.data.Champs.QuestionChamp;
import work.droit.data.Question;
import work.droit.gui.ApiController;
import work.util.data.io.ManipFile;
import work.util.data.table.Tables.Record;

public class QuestionSearch
{
	private Map<Integer, String>	cacheQuestionR	= null;
	private Map<Integer, String>	cacheQuestionQ	= null;

	public QuestionSearch()
	{
		cacheQuestionR = new HashMap<Integer, String>();
		cacheQuestionQ = new HashMap<Integer, String>();
	}

	public List<Question> findQuestions(String searchPattern)
	{
		Question questionTmp = new Question();
		questionTmp.setChamp(Question.name, "");
		List<Record<QuestionChamp>> jurisprudences = questionTmp.searchListRecords(Question.name, Question.name);

		List<Question> questionFound = new ArrayList<Question>();

		for (Record<QuestionChamp> rec : jurisprudences)
		{
			Question question = (Question) rec;
			String name = (String) question.getValue(Question.name);

			if (name.contains(searchPattern))
			{
				questionFound.add(question);
				continue;
			}
			if (findInContent(question, searchPattern))
			{
				questionFound.add(question);
				continue;
			}
		}

		return questionFound;
	}

	private boolean findInContent(Question jurisprudence, String searchPattern)
	{
		Integer id = (Integer) jurisprudence.getValue(Question.id);
		String content = cacheQuestionR.get(id);
		if (content == null)
		{
			content = ManipFile.getContent(ApiController.pathDocument + id + "r.txt");
			cacheQuestionR.put(id, content);
		}
		if (content.contains(searchPattern))
			return true;
		content = cacheQuestionQ.get(id);
		if (content == null)
		{
			content = ManipFile.getContent(ApiController.pathDocument + id + "q.txt");
			cacheQuestionQ.put(id, content);
		}
		if (content.contains(searchPattern))
			return true;
		return false;
	}
}
